package com.cx.common.secuity.feign;

import com.cx.common.core.constant.Constants;
import com.cx.common.core.constant.TokenConstants;
import com.cx.common.core.utils.ServletUtils;
import com.cx.common.core.utils.StringUtils;
import com.cx.common.core.utils.ip.IpUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * feign 请求拦截器
 *
 * @author ruoyi
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest httpServletRequest = ServletUtils.getRequest();
        if (StringUtils.isNotNull(httpServletRequest)) {
            Map<String, String> headers = ServletUtils.getHeaders(httpServletRequest);
            //传递token
            String authentication = headers.get(TokenConstants.AUTHENTICATION);
            if (StringUtils.isNotEmpty(authentication)) {
                requestTemplate.header(TokenConstants.AUTHENTICATION, authentication);
            }
            //传递链路ID
            String traceId = MDC.get(Constants.TRACE_ID);
            if (traceId != null) {
                requestTemplate.header(Constants.TRACE_ID, traceId);
            }


            // 配置客户端IP
            requestTemplate.header("X-Forwarded-For", IpUtils.getIpAddr());
        }
    }
}